<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名还曾" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名还曾"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键自增" align="center" prop="id" />
      <el-table-column label="商品名还曾" align="center" prop="productName" />
      <el-table-column label="商品品牌id" align="center" prop="productBrandId" />
      <el-table-column label="商品分类id" align="center" prop="productCategoryId" />
      <el-table-column label="规格属性id" align="center" prop="productRule" />
      <el-table-column label="商品描述" align="center" prop="productContent" />
      <el-table-column label="商品图片" align="center" prop="productUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品轮播图片" align="center" prop="productUrls" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productUrls" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品上下架状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.productStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="步骤" align="center" prop="step" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-steps :active="active" finish-status="success">
          <el-step title="商品基本信息"></el-step>
          <el-step title="商品规格信息"></el-step>
          <el-step title="商品描述信息"></el-step>
        </el-steps>



        <div v-show="active==1">

          <el-row :gutter="20">
            <el-col :span="10">
              <div class="grid-content bg-purple">
                <el-form-item label="商品名" prop="productName">
                  <el-input v-model="form.productName" placeholder="请输入商品名" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="grid-content bg-purple">
                <el-form-item label="商品品牌" prop="productBrandId">
                  <el-select v-model="form.productBrandId" placeholder="请选择商品品牌">
                    <el-option
                      v-for="item in branList"
                      :key="item.brandId"
                      :label="item.brandNameCn"
                      :value="item.brandId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>

          </el-row>


          <el-row :gutter="20">
            <el-col :span="15">
              <div class="grid-content bg-purple">
                <el-form-item label="商品分类id" prop="productCategoryId">
                  <el-cascader
                    v-model="form.productCategoryId"
                    :options="categoryList"
                    :props="{ expandTrigger: 'hover',value:'id', label:'name',children:'chirdenList' }"></el-cascader>
                </el-form-item>
              </div>
            </el-col>


          </el-row>

          <el-form-item label="商品图片" prop="productUrl">
            <image-upload v-model="form.productUrl"/>
          </el-form-item>
          <el-form-item label="商品轮播图片" prop="productUrls">
            <image-upload v-model="form.productUrls"/>
          </el-form-item>


          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="商品上下架状态" prop="productStatus">
                <el-radio-group v-model="form.productStatus">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

        </div>


        <div v-show="active==2">
          <div class="grid-content bg-purple">
            <el-form-item label="规格属性id" prop="productRule">

              <el-select v-model="form.productRule" placeholder="请选择规格属性" @change="updateRule">
                <el-option
                  v-for="item in ruleList"
                  :key="item.id"
                  :label="item.ruleName"
                  :value="item.ruleNo">
                </el-option>
              </el-select>

            </el-form-item>
            <br>


            <el-table
              :data="tableData"
              style="width: 100%">
              <el-table-column width="180" v-for="tableHeader in tableHeaderList"
              v-bind:prop="tableHeader.prop"
              :label="tableHeader.label">

                <template slot-scope="scope">

                  <image-upload v-if="tableHeader.prop.indexOf('images') > -1"  :limit="1" v-model="scope.row[tableHeader.prop]"/>
                  <el-input-number  v-else-if="tableHeader.prop.indexOf('price') > -1" v-model="scope.row[tableHeader.prop]"
                                    :min="1" :max="9999" label="描述文字"></el-input-number>
                  <span v-else>
                    {{scope.row[tableHeader.prop]}}
                  </span>
                </template>

              </el-table-column>

            </el-table>


          </div>
        </div>
        <div v-show="active==3">
          <el-form-item label="商品描述">
            <editor v-model="form.productContent" :min-height="192"/>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="pre" v-show="active>1">上一步</el-button>
        <el-button style="margin-top: 12px;" @click="next" v-show="active<3">下一步</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct,selectBrandAll } from "@/api/product/product";

import {listCategoryThree} from "@/api/product/category"
import {listRuleinfo}   from "@/api/product/rule"
export default {
  name: "Product",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      active:1,
      stepCn:{
        1:'商品基本信息',
        2:'商品规格信息',
        3:'商品描述信息'
      },
      stepTitle:"",
      branList:[],
      categoryList:[],
      ruleList:[],
      tableHeaderList:[

      ],

      tableData:[
      ]



    };
  },
  created() {
    this.getList();
    this.swtichStepCn();
    this.initRuleList();
    this.initBrandList();
    this.initCategoryList();
  },
  methods: {

    updateRule(ruleNo){

      this.tableHeaderList = [];
      let ruleInfo = {};
      this.ruleList.forEach(item =>{
        if (item.ruleNo === ruleNo) {
          ruleInfo = item;
        }
      });
      let ruleAttrTemplateList = JSON.parse(ruleInfo.ruleAttrTemplate);

      // 生成笛卡尔乘积
      function cartesianProduct(...arrays) {
        return arrays.reduce((acc, array) => {
          return acc.flatMap(d => array.map(e => [d, e].flat()));
        }, [[]]);
      }

      // 提取属性列表
      const attrLists = ruleAttrTemplateList.map(item => item.attrList);

      // 生成所有组合
      const combinations = cartesianProduct(...attrLists);

      // 生成表头
      ruleAttrTemplateList.forEach((item, index) => {
        this.tableHeaderList.push({ prop: `attrName${index}`, label: item.attrName });
      });

      // 初始化表头
      this.initTableHeaderList();

      // 生成表格数据
      this.tableData = combinations.map(combination => {
        const row = {};
        combination.forEach((value, index) => {
          row[`attrName${index}`] = value;
        });
        return row;
      });


      //拼接sku
      let tableData = this.tableData;
      tableData.forEach(item =>{
        let itemSkuList = []
        for (let itemKey in item) {
          if(itemKey.indexOf("attrName") > -1){
            itemSkuList.push(item[itemKey])
          }
        }
        item['sku'] = itemSkuList.join(",");
      })

      this.tableData = tableData;

    },

    initTableHeaderList(){
      this.tableHeaderList.push(
        { prop:"price", label:"价格"},
        { prop:"images", label:"图片"})
    },
    initRuleList(){
      listRuleinfo({ruleStatus:0}).then(res =>{
        if(res.code === 200){
          this.ruleList = res.data.rows;
        }
      })
    },
    initBrandList(){
      selectBrandAll().then(res =>{
        if(200 === res.code){
          this.branList = res.data;
        }
      })
    },
    initCategoryList(){
      listCategoryThree().then(res =>{
        if(200 === res.code){
          this.categoryList = res.data;
        }
      })
    }
    ,
    swtichStepCn(){
      this.stepTitle = this.stepCn[this.active];
    },
    pre() {
      this.active--;
      this.swtichStepCn();
    },
    next() {
      this.active++;
      this.swtichStepCn();
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        productName: null,
        productBrandId: null,
        productCategoryId: null,
        productRule: null,
        productContent: null,
        productUrl: null,
        productUrls: null,
        productStatus: null,
        step: null,
        createDate: null,
        updateDate: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        let form = response.data;
        let productCategoryIdList =[]
        form.productCategoryId.split(",").forEach(item =>{
          productCategoryIdList.push(1*item);
        })
        this.updateRule(form.productRule);
        let tableData = form.skuList;
        tableData.forEach(item =>{
          let strings = item['sku'].split(",");
          strings.forEach((stringsItem,index) =>{
            item[`attrName${index}`] = stringsItem;
          })
        })
        this.tableData = tableData;
        form.productCategoryId = productCategoryIdList;
        this.form = form;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form['skuList'] = this.tableData;
          this.form.productCategoryId = this.form.productCategoryId.join(",");
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          this.active=1;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
